using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Context;
using System.Collections;

namespace PHSRAG.Insight21.Admin.Controls
{
	/// <summary>
	///	User control that adds a lab to the database.
	/// </summary>
	public partial class AddAdminLab : System.Web.UI.UserControl
	{
		#region Constants
		private const string LabBasicInfoTableName = "Lab";
		private const string ClosePopupClientScriptKey = "ScriptKey_DD4997EF-3941-4a54-98BA-11FF8A9F633B";

		private const string LabsKey			= "Labs_8DD4FB62-755A-418f-B73A-07E79FA2A5B5";
		private const string LabNameKey			= "LabName_8DD4FB62-755A-418f-B73A-07E79FA2A5B5";
		private const string UsernameKey		= "Username_8DD4FB62-755A-418f-B73A-07E79FA2A5B5";
		private const string LastNameKey		= "LastName_8DD4FB62-755A-418f-B73A-07E79FA2A5B5";
		private const string FirstNameKey		= "FirstName_8DD4FB62-755A-418f-B73A-07E79FA2A5B5";
		private const string OrganizationIDKey	= "OrganizationID_8DD4FB62-755A-418f-B73A-07E79FA2A5B5";

		#endregion

		#region Private Variables
		/// <summary>Policy used for caching objects to be used across pages. </summary>
		private	Policy.ICachePolicy		pageCachePolicy;
		/// <summary>Policy used for caching business objects.</summary>
		private	Policy.ICachePolicy		objectCachePolicy;
		#endregion

		#region Event Handlers
		/// <summary>
		/// Sets the pop up page title and adds window close code for cancel button.
		/// </summary>
		/// <param name="sender">The object raising the event.</param>
		/// <param name="e">Information about the event itself.</param>
		protected void Page_Load(object sender, System.EventArgs e)
		{
			if (!IsPostBack) 
			{				
				((HtmlGenericControl)Page.FindControl("pageTitle")).InnerText = "Add Lab";
				cancel.Attributes["onclick"] = "window.close()";
			}
		}		
		/// <summary>
		/// Creates a new lab object, adds a table and a new row to the table
		/// and persists the lab the the database.
		/// </summary>
		/// <param name="sender">The object raising the event.</param>
		/// <param name="e">Information about the event itself.</param>
		protected void OnSave(object sender, System.EventArgs e)
		{
			try 
			{
				if (labName.Text.Trim() != string.Empty) 
				{
					UserContext userContext = objectCachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
					System.Diagnostics.Debug.Assert(userContext != null);

					Lab lab = new Lab(objectCachePolicy);
					DataTable labTable = lab.GetDataContainer().Tables.Add(LabBasicInfoTableName);
					labTable.Columns.Add("DomainUserId", typeof(int));
					labTable.Columns.Add("OrganizationId", typeof(int));
					labTable.Columns.Add("Name", typeof(string));
					labTable.Columns.Add("Description", typeof(string));

					int selectedOrganizationID = organizationSelectors.SelectedOrganizationID;
					string newLabName = labName.Text.Trim();

					// Add cache new lab criteria to be used by search labs page to retrieve the newly created lab when the
					// pop up closes and search labs page refreshes
					pageCachePolicy.Cache(LabNameKey, newLabName);
					pageCachePolicy.Cache(OrganizationIDKey, selectedOrganizationID);
					pageCachePolicy.Cache(UsernameKey, string.Empty);
					pageCachePolicy.Cache(LastNameKey, string.Empty);
					pageCachePolicy.Cache(FirstNameKey, string.Empty);
					pageCachePolicy.UnCache(Keys.SearchLabsPageKey);

					DataRow newLabRow = labTable.NewRow();
					newLabRow["DomainUserId"] = userContext.DomainUserId;
					newLabRow["OrganizationId"] = selectedOrganizationID;
					newLabRow["Name"] = newLabName;
					newLabRow["Description"] = labDescription.Text.Trim();	
					labTable.Rows.Add(newLabRow);
					lab.Save(Utility.DataAccess.GetConnectionString(), LabCommandType.Add);

					// close the popup and refresh the opening page so that it displays the newly added lab
					Page.ClientScript.RegisterClientScriptBlock(GetType( ), ClosePopupClientScriptKey, "<script language='javascript'>window.opener.document.location.href='../Admin/AdminSearchLabs.aspx';window.close();</script>");
				}
				else
					annunciator.Message = "Please Provide Lab Name.";
			} 
			catch (Exception ex) 
			{
				annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
				Utility.ExceptionReport.WriteToEventLog("AddAdminLab", ex, true, Utility.ExceptionReport.ReportType.Error);
			}
		}

		#endregion

		#region Web Form Designer generated code
		/// <summary>
		/// Handles wiring up of page events.
		/// </summary>
		/// <param name="e">Information about the event itself.</param>
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);

			objectCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
			pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];

			ID = "addAdminLab";
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
		}
		#endregion
	}
}
